package dat255.calendarclock.view;

import java.util.GregorianCalendar;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.WindowManager;
import android.widget.Button;

/**
 * The button in the month view
 * @author Marcus Hultman
 *
 */
public class MonthCalendarDateButton extends Button {

	// Fields
	
	private static float TEXT_SIZE = 1/2f;
	
	private static int textColorPrimary = Color.BLACK;
	private static int textColorSecondary = Color.RED;
	
	private static int colorSelected = Color.BLUE;
	private static int colorUnselected = Color.LTGRAY;
	
	private Paint paint = new Paint();
	private Paint textPaint = new Paint();
	
	private boolean isSelected = false; 
	
	private GregorianCalendar date;
	
	// Constructor
	
	public MonthCalendarDateButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		paint.setColor(colorUnselected);
	}
	
	// Public Methods
	
	public GregorianCalendar getDate() {
		return this.date;
	}
	public void setDate(GregorianCalendar date) {
		this.date = date;
	}
	
	/**
	 * 
	 * @param isCurrentMonth if the month is the current month
	 */
	public void setCurrentMonth(boolean isCurrentMonth){
		textPaint.setColor(isCurrentMonth ? textColorPrimary
				: textColorSecondary);
	}
	
	
	// Draw
	
	@Override
	protected int getSuggestedMinimumHeight() {
		return 0;
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		
		int height = Math.min(
				MeasureSpec.getSize(widthMeasureSpec),
				MeasureSpec.getSize(widthMeasureSpec)
						* ((WindowManager) getContext().getSystemService(
								Context.WINDOW_SERVICE)).getDefaultDisplay()
								.getHeight() / 500);
		setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), height);
	}
	
	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		super.onLayout(changed, left, top, right, bottom);
		textPaint.setTextSize(TEXT_SIZE * getWidth());
	}
	
	
	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
		String number = Integer.toString(date.get(GregorianCalendar.DATE));
		canvas.drawText(number,
				getWidth() / 2 - textPaint.measureText(number) / 2, 
				2 * getHeight() / 3, 
				textPaint);
	}

	/**
	 * Toggles the button
	 */
	public void toggle() {
		isSelected = !isSelected;
		if (isSelected)
			paint.setColor(colorSelected);
		else
			paint.setColor(colorUnselected);
	}

	
	
}
